package com.yzycoc.hamster.demo.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.spel.ast.NullLiteral;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class ImageDownloadUtil {

    private final File downloadDir;
    private final File recordFile;
    private final File insertedFile;
    private final File sqlOutputFile;


    private final Set<String> downloadedUrls = new HashSet<>();
    private final Set<String> insertedUrls = new HashSet<>();

    public ImageDownloadUtil(String subDir) {
        String basePath = System.getProperty("user.dir") + "/image";
        this.downloadDir = FileUtil.mkdir(subDir);
        this.recordFile = FileUtil.file(basePath + "/downloaded.json");
        this.insertedFile = FileUtil.file(basePath + "/inserted.json");
        this.sqlOutputFile = FileUtil.file(basePath + "/inserted.sql");

        // 加载已下载记录
        if (recordFile.exists()) {
            JSONArray arr = JSON.parseArray(FileUtil.readUtf8String(recordFile));
            for (Object obj : arr) {
                downloadedUrls.add(obj.toString());
            }
        }

        // 加载已生成SQL的记录
        if (insertedFile.exists()) {
            JSONArray arr = JSON.parseArray(FileUtil.readUtf8String(insertedFile));
            for (Object obj : arr) {
                insertedUrls.add(obj.toString());
            }
        }
    }

    /**
     * 下载图片到指定目录，若已下载则跳过
     */
    public File download(String urlStr) {
        try {
            if (downloadedUrls.contains(urlStr)) {
                log.info("已下载过：{}", urlStr);
                return null;
            }

            URL url = new URL(urlStr);
            String fileName = IdUtil.simpleUUID() + "." + FileUtil.extName(urlStr);
            File destFile = FileUtil.file(downloadDir, fileName);

            try (InputStream in = url.openStream()) {
                FileUtil.writeFromStream(in, destFile);
            }

            downloadedUrls.add(urlStr);
            FileUtil.writeUtf8String(JSON.toJSONString(downloadedUrls), recordFile);

            log.info("下载完成：{}", destFile.getAbsolutePath());
            return destFile;

        } catch (Exception e) {
            log.error("下载失败: {}", urlStr, e);
            return null;
        }
    }

    /**
     * 根据url和type生成插入SQL，如果已生成过则跳过
     */
    public String generateInsertSql(String url, String types) {
        String fileName = FileUtil.getName(url);
        return generateInsertSql(url, types, fileName, "NULL");
    }


    /**
     * 根据url和type生成插入SQL，如果已生成过则跳过
     */
    public String generateInsertSql(String url, String types, String name, String remark) {
        if (insertedUrls.contains(url)) {
            //log.info("已生成SQL：{}", url);
            return null;
        }
        String createDate = DateUtil.now();
        String sql = StrUtil.format(
                "INSERT INTO `background`(`create_date`, `create_name`, `url`, `pc`, `is_user`, `height`, `width`, `types`, `user`, `remark`) " +
                        "VALUES ('{}', '{}', '{}', 1, b'1', NULL, NULL, '{}', NULL, {});",
                createDate, name, url, types, remark
        );
        // 添加记录并保存
        insertedUrls.add(url);
        FileUtil.writeUtf8String(JSON.toJSONString(insertedUrls), insertedFile);
        // 追加SQL到文件
        FileUtil.appendString(sql + "\n", sqlOutputFile, StandardCharsets.UTF_8);
        //log.info("已写入SQL：{}", sql);
        return sql;
    }
}
